package com.nowcoder.topic.string.middle;

import java.util.PriorityQueue;

/**
 * NC379 重排字符串
 * @author d3y1
 */
public class NC379{
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     *
     * @param str string字符串
     * @return string字符串
     */
    public String rearrangestring (String str) {
        int len = str.length();
        int[] charCount = new int[26];
        PriorityQueue<Letter> maxHeap = new PriorityQueue<>((o1, o2)->(o2.count-o1.count));

        // 统计字符次数
        for(int i=0; i<len; i++){
            charCount[str.charAt(i)-'a']++;
        }

        // build maxHeap
        for(int i=0; i<26; i++){
            if(charCount[i] > 0){
                maxHeap.add(new Letter((char)('a'+i), charCount[i]));
            }
        }

        // 贪心: 最多字符+次多字符
        StringBuilder sb = new StringBuilder();
        Letter first,second;
        while(maxHeap.size() >= 2){
            first = maxHeap.poll();
            second = maxHeap.poll();
            sb.append(first.ch);
            sb.append(second.ch);
            if(first.count > 1){
                first.count--;
                maxHeap.add(first);
            }
            if(second.count > 1){
                second.count--;
                maxHeap.add(second);
            }
        }

        if(!maxHeap.isEmpty()){
            first = maxHeap.poll();
            if(first.count > 1){
                return "";
            }else{
                sb.append(first.ch);
            }
        }

        return sb.toString();
    }

    /**
     * 英文字母
     */
    private class Letter {
        char ch;
        int count;

        public Letter(char ch, int count){
            this.ch = ch;
            this.count = count;
        }
    }
}